package cmsi.Controller;

import net.lcheng.commons.utils.ParseMD5;
import net.lcheng.model.User;
import net.lcheng.service.UserService;
import net.lcheng.vo.LoginEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Properties;

/**
 * Created by zwr on 2016/6/28 0028.
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    /**登录get*/
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String home(Model model,HttpServletRequest request) throws IOException {
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if (currentUser.isAuthenticated()) {
            return "redirect:/my";
        }
        else {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.indexOf("MicroMessenger") > 0) {
                //**跳转到微信授权页面*/
                Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
                String wxLoginUrl = properties.getProperty("wxLoginUrl");
                String wxAPPID = properties.getProperty("wxAPPID");

                String targetUrl = "";
                String redirectUri = wxLoginUrl+"?target_url=" + targetUrl;
                String login_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxAPPID +
                        "&redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8").toString() +
                        "&response_type=code" +
                        "&scope=snsapi_userinfo" +
                        "&state=STATE" +
                        "&connect_redirect=1#wechat_redirect";
                return "redirect:" + login_url;
            } else {
                if (!model.containsAttribute("LoginEntity")) {
                    model.addAttribute("LoginEntity", new LoginEntity());
                }
                return "login";
          }
        }
    }


    /***
     * 用户登陆
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Model model, @Valid @ModelAttribute("LoginEntity") LoginEntity user, BindingResult result, Errors errors) {
        if (result.hasErrors()) {
            return "login";
        }
        model.addAttribute("errorType", 0);
        User userModel = userService.getUserByPhone(user.getUserPhone());
        if (userModel != null) {
            String inputPwd = ParseMD5.parseStrToMd5L32(user.getUserPwd());
            if (!userModel.getUserPwd().equals(inputPwd)) {
//                model.addAttribute("errorType",1);
                errors.rejectValue("userPwd", "userPwd", "登录密码错误");//这个函数有好几个重载的变体
                model.addAttribute("errorType", 1);
                model.addAttribute("error", "登录密码错误");
                return "login";
            }
            //登录成功
            SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUserPhone(), user.getUserPwd()));
            SecurityUtils.getSubject().getSession().setAttribute("userPhone",user.getUserPhone());
            /**获取登录前的URL*/
            SavedRequest savedRequest = null;
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession(false);
            if (session != null) {
                savedRequest = (SavedRequest) session.getAttribute("shiroSavedRequest");
            }
            if (savedRequest == null) {
                return "redirect:/home";
            } else return "redirect:" + savedRequest.getRequestUrl();
        } else {
            errors.rejectValue("userPhone", "userPhone", "用户不存在");//这个函数有好几个重载的变体
            return "login";
        }
    }
}
